package com.tyx.chargingpile.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tyx.chargingpile.Enum.ServiceExceptionEume;
import com.tyx.chargingpile.Enum.ServiceMessageEume;
import com.tyx.chargingpile.pojo.ChargingStartEndRecord;
import com.tyx.chargingpile.service.ChargingPileService;
import com.tyx.chargingpile.service.ChargingStartEndRecordService;
import com.tyx.chargingpile.service.HttpAPIService;
import com.tyx.chargingpile.service.MessageService;
import com.tyx.chargingpile.service.exception.ServiceExcep;
import com.tyx.chargingpile.util.DateUtils;
import com.tyx.chargingpile.util.Util;
import com.tyx.chargingpile.vo.HttpResult;
import com.tyx.chargingpile.vo.SocketResponseResult;
import io.netty.channel.ChannelHandlerContext;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 电桩开启上行
 */
@Service("chargingPileOpenUp")
public class ChargingPileOpenUp  implements ChargingPileService {
    @Value("${chargingback.url}")
    private String url;
    @Autowired
    HttpAPIService httpAPIService;

    @Autowired
    private ChargingStartEndRecordService chargingStartEndRecordService;

    private final static Logger LOGGER = LoggerFactory.getLogger(ChargingPileOpenUp.class);
    @Override
    public SocketResponseResult execute(ChannelHandlerContext channelHandlerContext, byte[] context) throws Exception {
        String commandId = MessageService.getCommandControl(context);
        String channelId = channelHandlerContext.channel().id().toString();
        Map<String,String> map = MessageService.analysisMessage(context, ServiceMessageEume.OPEND.getUpLinePath());
        checkData(map);
        // 开启充电桩成功，这时更新记录，登记开启时间
        String orderNum = map.get("orderNum");
        String pileNum = map.get("pileNum");
        // 对枪口编号，进行转换，如果前面有0的，转换掉
        String gunpointNum = Integer.parseInt(map.get("gunpointNum")) + "";
        // 桩编号，去掉前面一个0
        pileNum = pileNum.substring(1,pileNum.length());
        // 命令反馈
        String commandBack = map.get("commandBack");
        LOGGER.info("客户端"+channelId+",指令控制编号："+commandId+",桩编号:" + pileNum + ",枪口编号--" + gunpointNum + ",订单编号--" + orderNum + ",远程开启充电桩上送：开启充电桩成功");
        ChargingStartEndRecord chargingStartEndRecord = chargingStartEndRecordService.find(pileNum,gunpointNum,orderNum);
        boolean result = sendOpenCharging(pileNum,gunpointNum,orderNum,commandBack,channelId,commandId);
        if (chargingStartEndRecord != null){
            chargingStartEndRecord.setStartTime(DateUtils.now());
            chargingStartEndRecord.setStartCommand(commandBack);
            if (result){
                chargingStartEndRecord.setSendStartStatus("1");
            }else {
                chargingStartEndRecord.setSendStartStatus("2");
            }
            chargingStartEndRecordService.add(chargingStartEndRecord);
        }
        return null;
    }

    @Override
    public SocketResponseResult execute(ChannelHandlerContext channelHandlerContext, Map data) throws Exception {
        return null;
    }

    private boolean sendOpenCharging(String pileNum,String gunpointNum,String orderNum,String commandBack,String channelId,String commandId){
        try{
            JSONObject requestJson = new JSONObject();
            JSONObject dataJson = new JSONObject();
            if (commandBack.equals("FF")){
                dataJson.put("Result",1);
            }else {
                dataJson.put("Result",0);
            }
            dataJson.put("DeviceId",pileNum);
            dataJson.put("ChargePortIndex",gunpointNum);
            dataJson.put("OrderId",orderNum);
            requestJson.put("MainCMD",68);
            requestJson.put("SubCMD",2);
            requestJson.put("Data",dataJson);
            LOGGER.info("客户端"+channelId+",指令控制编号："+commandId+",桩编号:" + pileNum + ",枪口编号--" + gunpointNum + ",订单编号--" + orderNum + ",放电通知推送至后台：" + requestJson.toJSONString());
            HttpResult result = httpAPIService.doPost2Json(url,requestJson.toJSONString());
            if(result.getCode() != 200){
                LOGGER.info("客户端"+channelId+",指令控制编号："+commandId+",桩编号:" + pileNum + ",枪口编号--" + gunpointNum + ",订单编号--" + orderNum + ",放电通知推送至后台：" + false);
                return false;
            }
            LOGGER.info("客户端"+channelId+",指令控制编号："+commandId+",桩编号:" + pileNum + ",枪口编号--" + gunpointNum + ",订单编号--" + orderNum + ",放电通知推送至后台：" + true);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            LOGGER.info("客户端"+channelId+",指令控制编号："+commandId+",桩编号:" + pileNum + ",枪口编号--" + gunpointNum + ",订单编号--" + orderNum + ",放电通知推送至后台：报错" + e.getMessage());
            return false;
        }
    }

    /**
     * 报文业务校验
     * @param map
     * @throws ServiceExcep
     */
    private void checkData(Map<String,String> map) throws ServiceExcep {
        if(map == null){
            throw new ServiceExcep(ServiceExceptionEume.MESSAGEPARSINGERROR);
        }
        String orderNum = map.get("orderNum");
        String pileNum = map.get("pileNum");
        String gunpointNum = map.get("gunpointNum");
        String commandBack = map.get("commandBack");
        if (TextUtils.isEmpty(pileNum) || TextUtils.isEmpty(gunpointNum) ||TextUtils.isEmpty(orderNum) ||TextUtils.isEmpty(commandBack)){
            throw new ServiceExcep(ServiceExceptionEume.INCOMPLETEPARAMETERS);
        }
    }
}
